//
//  ITNetworkMonitorManager.m
//  ITBE
//
//  Created by ITBE on 2019/3/1.
//  Copyright © 2019 ITBE. All rights reserved.
//

#import "ITNetworkMonitorManager.h"

@implementation ITNetworkMonitorManager
+(instancetype)shareManager
{
    static ITNetworkMonitorManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ITNetworkMonitorManager alloc] init];
    });
    return manager;
}

-(void)startMonitorNetwork
{
    @weakify(self);
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        @strongify(self);
        if (self == nil) {
            return ;
        }
        self->networkStatus = status;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                self->networkName = @"unknown";
                if ([self.delegate respondsToSelector:@selector(connetNetworkWithStatus:)]) {
                    [self.delegate connetNetworkWithStatus:status];
                }
                break;
            }
            case AFNetworkReachabilityStatusNotReachable:
            {
                self->networkName = @"none";
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:
            {
                self->networkName = @"wwan";
                if ([self.delegate respondsToSelector:@selector(connetNetworkWithStatus:)]) {
                    [self.delegate connetNetworkWithStatus:status];
                }
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:
            {
                self->networkName = @"wifi";
                if ([self.delegate respondsToSelector:@selector(connetNetworkWithStatus:)]) {
                    [self.delegate connetNetworkWithStatus:status];
                }
                break;
            }
            default:
                break;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationNetworkChanged object:@(status)];
        [ITTrackManager.shareManager updateNetworkStatus:self->networkName];
    }];
    [manager startMonitoring];
}

-(AFNetworkReachabilityStatus)networkStatus
{
    return networkStatus;
}

-(NSString *)networkName
{
    return networkName ?: @"";
}
@end
